package tgc.edu.exam.web.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.custom.LayUiResult;
import tgc.edu.exam.custom.dict.service.TbClassStateService;
import tgc.edu.exam.custom.dict.service.TbClassTypeService;
import tgc.edu.exam.entity.CurriculumPlan;
import tgc.edu.exam.entity.Student;
import tgc.edu.exam.entity.TbClass;
import tgc.edu.exam.service.CurriculumPlanService;
import tgc.edu.exam.service.StudentService;
import tgc.edu.exam.service.TbClassService;
import tgc.edu.exam.service.TeacherService;
import tgc.edu.exam.web.form.CurriculumTableForm;
import tgc.edu.exam.web.form.TbClassForm;

@Controller
@RequestMapping(value="/tbClass")
public class TbClassController extends CommonController<TbClass, UUID, TbClassForm> {
	@Autowired
	private TbClassStateService csService;
	@Autowired
	private TbClassTypeService ctService;
	@Autowired
	private TeacherService tService;
	@Autowired
	private StudentService stuService;
	@Autowired
	private TbClassService tcService;
	@Autowired
	private CurriculumPlanService cservice;

	@Override
	public void edit(TbClassForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		map.put("state", csService.findAll());
		map.put("type", ctService.findAll());
		map.put("teacher", tService.findAll());
		super.edit(form, map);
	}
	
	@RequestMapping(value="/view")
	public void view(TbClassForm form, ModelMap map){
		map.put("state", csService.findAll());
		map.put("type", ctService.findAll());
		map.put("teacher", tService.findAll());
		TbClass model= new TbClass();
		UUID id = form.getId();
		List<CurriculumTableForm> tableformlist = new ArrayList<>();
		if(id!=null) {
			model=tcService.findById(id);
			List<CurriculumPlan> clist = cservice.findByTbClassId(id);
			List<CurriculumTableForm> findBydtkc = cservice.findBydtkc(clist);//处理相同的文字
			tableformlist = cservice.findTr(findBydtkc);//处理空白单元格
		}
		map.put("model1", tableformlist);
		map.put("model", model);
	}
	
	@Override
	public Object save(TbClassForm form) {
		if(form.getId() == null) {
			form.setIsUsed(true);			
		}
		return super.save(form);
	}

	@Override
	public Specification<TbClass> buildSpec(TbClassForm form) {
		Specification<TbClass> specification = new Specification<TbClass>() {

			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<TbClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(StringUtils.hasText(form.getName())) {
					Predicate name = cb.like(root.get("name"), "%"+form.getName()+"%");
					rules.add(name);
				}
				if(StringUtils.hasText(form.getSubject())) {
					Predicate difficultylevel = cb.like(root.get("subject"), "%"+form.getSubject()+"%");
					rules.add(difficultylevel);
				}
				if(StringUtils.hasText(form.getBtnType())){
					if(form.getBtnType().equals("yes")) {
						Predicate difficultylevel = cb.equal(root.get("classStatus").get("state"), "结业");
						rules.add(difficultylevel);
					}else {
						Predicate difficultylevel = cb.notEqual(root.get("classStatus").get("state"), "结业");
						rules.add(difficultylevel);
					}				
				}else {
					Predicate difficultylevel = cb.notEqual(root.get("classStatus").get("state"), "结业");
					rules.add(difficultylevel);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
	
	/**
	 * 班级分组页面
	 */
	@RequestMapping(value="/groupMsg")
	public void groupMsg(String id, ModelMap map) {
		TbClass tbclass = tcService.findById(UUID.fromString(id));
		if(tbclass.getClassNumber() != null) {
			if(tbclass.getClassNumber() == 0) {
				tbclass = null;
			}else {
				map.put("stu", stuService.findByTbClassId(tbclass.getId()));
			}
		}else {
			tbclass = null;
		}
		map.put("id", id);
		map.put("tbClass", tbclass);
	}
	
	/**
	 * 分组修改
	 */
	@RequestMapping(value="/groupUpdata")
	@ResponseBody
	public Object groupUpdata(String stuid, String groupNumber) {
		Student stu = stuService.findById(UUID.fromString(stuid));
		stu.setGroupNumber(groupNumber);
		stu.setGroup1(false);
		stuService.save(stu);
		return LayUiResult.getResult("ok");
	}
	
	/**
	 * 修改组长
	 */
	@RequestMapping(value="/updataGroupLeader")
	@ResponseBody
	public Object updataGroupLeader(String stuid, String groupNumber) {
		TbClass tbClass = stuService.findById(UUID.fromString(stuid)).getTbClass();
		List<Student> stu = stuService.findByTbClassId(tbClass.getId());
		for(int i = 0; i < stu.size(); i++) {
			Student s = stu.get(i);
			if(s.getGroupNumber().equals(groupNumber)) {
				s.setGroup1(false);
				stuService.save(s);
			}
		}
		Student stu1 = stuService.findById(UUID.fromString(stuid));
		stu1.setGroup1(true);
		stuService.save(stu1);
		return LayUiResult.getResult("ok");
	}
	
	/***
	 * 班级分组
	 * @param zs
	 * @param tbClassId
	 */
	@RequestMapping(value="/grouping")
	@ResponseBody
	public Object grouping(Integer classNumber, String tbClassId, String order1) {
		try {
			String[] split = order1.split(",");
			List<Sort.Order> orders = new ArrayList<>();
			for(int i = 0; i < split.length; i++) {
				orders.add(new Sort.Order(Sort.Direction.DESC, split[i]));	
				System.out.println(split[i]);
			}
			UUID id = UUID.fromString(tbClassId);
			TbClass tbclass = tcService.findById(id);
			tbclass.setClassNumber(classNumber);
			List<Student> stu = stuService.findByTbClassId(Sort.by(orders), id);
			
			tcService.save(tbclass);
			
			int a = 1;
			for(int i = 0; i < stu.size(); i++) {
				Student s = stu.get(i);
				s.setGroupNumber(a+"");
				stuService.save(s);
				a++;
				System.out.println(a);
				if(a > classNumber) {
					a = 1;
				}
			}
			return LayUiResult.getResult("ok");
		} catch (Exception e) {
			return LayUiResult.getErrorResult("分组失败");		
		}
	}
	
	/**
	 * 班级分组数据
	 */
	@RequestMapping(value="/grouping1")
	public void grouping1(String id, ModelMap map) {
		List<Student> stu = stuService.findByTbClassId(UUID.fromString(id));
		map.put("stu", stu);
	}
	
	/**
	 * 判断班级是否已分组
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/groupingYZ")
	@ResponseBody
	public Object groupingYZ(String id) {
		TbClass tbclass = tcService.findById(UUID.fromString(id));
		if(tbclass.getClassNumber() != null) {
			if(tbclass.getClassNumber() != 0) {
				return LayUiResult.getErrorResult("已分组");				
			}else {
				return LayUiResult.getResult("没有分组");				
			}
		}else {
			return LayUiResult.getResult("没有分组");
		}
	}

}
